//
//  BBDHealthInformationViewController.m
//  棒棒哒
//
//  Created by rimi on 15/8/3.
//  Copyright (c) 2015年 rimi. All rights reserved.
//

#import "BBDHealthInformationViewController.h"
#import <MapKit/MapKit.h>
#import <CoreLocation/CoreLocation.h>
#import "CBAutoScrollLabel.h"
#import "NetRequest.h"
#import "Masonry.h"
#import "HealthyInfomationTableViewCell.h"
#import "NewsViewController.h"
#import "ChineseToPinyin.h"

@interface BBDHealthInformationViewController ()<CLLocationManagerDelegate, UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, strong) UIScrollView      *scrollView;
@property (nonatomic, strong) CLLocationManager *locationManager;
@property (nonatomic, strong) UIImageView       *weatherBackView;
@property (nonatomic, strong) UILabel           *name;
@property (nonatomic, strong) NSMutableArray    *weatherArray;
@property (nonatomic, strong) NSTimer           *time;
@property (nonatomic, strong) NSDateFormatter   *date;
@property (nonatomic, strong) UILabel           *dateLabel;
@property (nonatomic, strong) UIImageView       *showView;
@property (nonatomic, strong) UITableView       *tableView;
@property (nonatomic, strong) NSMutableArray    *infoArray;
@property (nonatomic, strong) NSArray           *imageArray;
@property (nonatomic, strong) NSString          *cityString;

@end

static NSString *identifier = @"HEALTHYCELL";

@implementation BBDHealthInformationViewController


- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    NSThread *thread = [[NSThread alloc]initWithTarget:self selector:@selector(startTimer) object:nil];
    [thread start];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor colorWithPatternImage:IMAGNAME(@"天气背景.jpg")];
    [self initializeDataSource];
    [self initializeUserInterface];
}

- (void)initializeDataSource
{
    NSString *hanziText = @"我是中国人";
    if ([hanziText length]) {
        NSMutableString *ms = [[NSMutableString alloc] initWithString:hanziText];
        if (CFStringTransform((__bridge CFMutableStringRef)ms, 0, kCFStringTransformMandarinLatin, NO)) {
            NSLog(@"pinyin: %@", ms);
        }
        if (CFStringTransform((__bridge CFMutableStringRef)ms, 0, kCFStringTransformStripDiacritics, NO)) {
            NSLog(@"pinyin: %@", ms);
        }  
    }
    _weatherArray = [NSMutableArray array];
    _infoArray = [NSMutableArray array];
    _imageArray = @[IMAGNAME(@"0.jpg"),IMAGNAME(@"1.jpg"),IMAGNAME(@"2.jpg"),IMAGNAME(@"3.jpg"),IMAGNAME(@"4.jpg"),IMAGNAME(@"5.jpg"),IMAGNAME(@"6.jpg")];
}

- (void)initializeUserInterface
{
    //配置展示视图
    self.automaticallyAdjustsScrollViewInsets = NO;
    if (!_scrollView) {
        _scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 64, SCREEN_WIDTH, SCREEN_HEIGHT / 3)];
        _scrollView.contentSize = CGSizeMake(SCREEN_WIDTH, 0);
        _scrollView.pagingEnabled = YES;
        _scrollView.showsHorizontalScrollIndicator = NO;
        [self.view addSubview:_scrollView];
    }
    
    //配置展示图片
    if (!_showView) {
        _showView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT / 3)];
        _showView.image = IMAGNAME(@"展示图片.jpg");
        [_scrollView addSubview:_showView];
    }
    
    
    //配置TableView
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, _scrollView.frame.size.height + 84, SCREEN_WIDTH, SCREEN_HEIGHT - _scrollView.frame.size.height - 84 - TAB_BAR_HIGHT) style:0];
        
        _tableView.alpha = 0.5;
        [_tableView registerNib:[UINib nibWithNibName:@"HealthyInfomationTableViewCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:identifier];
        _tableView.delegate = self;
        _tableView.dataSource = self;
//        _tableView.backgroundColor = [UIColor colorWithPatternImage:IMAGNAME(@"天气背景.jpg")];
        _tableView.backgroundColor = [UIColor colorWithWhite:0 alpha:0];
        [self.view addSubview:_tableView];
    }
    
    
    
    //配置天气信息
    if (!_weatherBackView) {
        _weatherBackView = [[UIImageView alloc]initWithImage:IMAGNAME(@"天气背景.jpg")];
        _weatherBackView.alpha = 0.9;
        [_showView addSubview:_weatherBackView];
        [_weatherBackView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.mas_equalTo(@0);
            make.top.mas_equalTo(@0);
            make.size.mas_equalTo(CGSizeMake(100, SCREEN_HEIGHT / 3));
        }];
    }
    
    //判断是否允许定位
    if (![CLLocationManager locationServicesEnabled]) {
        UIAlertController * alertController = [UIAlertController alertControllerWithTitle:@"温馨提示"
                                                                                  message:@"当前应用不支持定位，请在设置界面开启"
                                                                           preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction * action = [UIAlertAction actionWithTitle:@"确定"
                                                          style:UIAlertActionStyleDefault
                                                        handler:^(UIAlertAction *action) {
                                                            
                                                        }];
        [alertController addAction:action];
        [self presentViewController:alertController
                           animated:YES
                         completion:nil];
    }
    //配置定位
    self.locationManager = ({
        CLLocationManager * locationManager = [[CLLocationManager alloc] init];
        locationManager.delegate = self;
        [locationManager requestAlwaysAuthorization];
        [locationManager requestWhenInUseAuthorization];
        locationManager.desiredAccuracy = kCLLocationAccuracyBest;
        locationManager.distanceFilter = 10.0f;
        [locationManager startUpdatingLocation];
        locationManager;
    });
    
    
}
#pragma mark - CLLocationManagerDelegate
- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status
{
    switch (status) {
        case kCLAuthorizationStatusNotDetermined:
            if ([self.locationManager respondsToSelector:@selector(requestAlwaysAuthorization)]) {
                [self.locationManager requestAlwaysAuthorization];
            }
            break;
        default:
            break;
    }
}
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
    NSLog(@"%@", error);
}

- (void)locationManager:(CLLocationManager *)manager
     didUpdateLocations:(NSArray *)locations
{
    CLLocation *currentLocation = [locations lastObject];
    CLGeocoder *geocoder = [[CLGeocoder alloc]init];
    [geocoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray *placemarks, NSError *error) {
        if (placemarks.count > 0) {
            CLPlacemark *placemark = [placemarks objectAtIndex:0];
            _name = [CustomLabel labelWithFrame:CGRectMake(0, 0, 0, 0) Text:placemark.locality FontSize:25 TextAlignment:NSTextAlignmentLeft TextColor:[UIColor whiteColor] BackGroundColor:[UIColor clearColor] CornerRadius:0 BorderWidth:0 BorderColor:nil];
            _name.numberOfLines = 0;
            [_weatherBackView addSubview:_name];
            [_name mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.mas_equalTo(@5);
                make.top.mas_equalTo(@10);
                make.size.mas_equalTo(CGSizeMake(_weatherBackView.frame.size.width, 40));
            }];

            _cityString = [[ChineseToPinyin pinyinFromChiniseString:_name.text]stringByReplacingOccurrencesOfString:@"SHI" withString:@""];
            
            [self netRequest:_cityString];
        }
    }];
    
    [self.locationManager stopUpdatingLocation];
    
}
#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _infoArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    HealthyInfomationTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    cell.titleLabel.text = _infoArray[indexPath.row][@"name"];
    cell.informationImage.image = _imageArray[indexPath.row];
    return cell;
}
#pragma mark -- UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    CGRect contentRect = [_infoArray[indexPath.row][@"content"] boundingRectWithSize:CGSizeMake(self.view.bounds.size.width * 2 / 3, DBL_MAX) options:NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName : [UIFont systemFontOfSize:16]} context:nil];
    return contentRect.size.height + 50;
}
- (BOOL)tableView:(UITableView *)tableView shouldHighlightRowAtIndexPath:(NSIndexPath *)indexPath
{
    NewsViewController *newVC = [[NewsViewController alloc]init];
    newVC.idNumber = [_infoArray[indexPath.row][@"id"]integerValue];
    newVC.titleName = _infoArray[indexPath.row][@"name"];
    [self.navigationController pushViewController:newVC animated:YES];
    return YES;
}

- (void)netRequest:(NSString *)string
{
    NSString *httpUrl = @"http://apis.baidu.com/heweather/weather/free";
    NSString *httpArg = [NSString stringWithFormat:@"city=%@", string];
    NetRequest *request = [[NetRequest alloc]init];
    [request request:httpUrl withHttpArg:httpArg success:^(id responseObject) {
        _weatherArray = responseObject[@"HeWeather data service 3.0"];
        //        NSLog(@"%@", _weatherArray[0][@"suggestion"]);
        UILabel *weatherLabel = [CustomLabel labelWithFrame:CGRectMake(0, 0, 0, 0) Text:[NSString stringWithFormat:@"%@˚", _weatherArray[0][@"now"][@"tmp"]] FontSize:25 TextAlignment:NSTextAlignmentLeft TextColor:[UIColor whiteColor] BackGroundColor:[UIColor clearColor] CornerRadius:0 BorderWidth:0 BorderColor:nil];
        [_weatherBackView addSubview:weatherLabel];
        [weatherLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(@5);
            make.top.mas_equalTo(_name.frame.size.height + 5);
            make.size.mas_equalTo(CGSizeMake(_weatherBackView.frame.size.width, 40));
        }];
        UIImageView *weatherImage = [CustomImageView imageViewWithFrame:CGRectMake(0, 0, 0, 0) Image:IMAGNAME(_weatherArray[0][@"now"][@"cond"][@"code"]) Alpha:0.8 CornerRadius:0 BorderWidth:0 BorderColor:nil];
        [_weatherBackView addSubview:weatherImage];
        [weatherImage mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(@5);
            make.top.mas_equalTo(@80);
            make.size.mas_equalTo(CGSizeMake(60, 60));
        }];
        UILabel *weatherNameLabel = [CustomLabel labelWithFrame:CGRectMake(0, 0, 0, 0) Text:_weatherArray[0][@"now"][@"cond"][@"txt"] FontSize:18 TextAlignment:NSTextAlignmentLeft TextColor:[UIColor whiteColor] BackGroundColor:nil CornerRadius:0 BorderWidth:0 BorderColor:nil];
        weatherNameLabel.textAlignment = NSTextAlignmentCenter;
        [_weatherBackView addSubview:weatherNameLabel];
        [weatherNameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(@15);
            make.top.mas_equalTo(@140);
            make.size.mas_equalTo(CGSizeMake(40, 20));
        }];
        static CBAutoScrollLabel *wearLabel = nil;
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
            wearLabel = [[CBAutoScrollLabel alloc]init];
            wearLabel.text = [NSString stringWithFormat:@"穿衣：%@", _weatherArray[0][@"suggestion"][@"drsg"][@"txt"]];
            wearLabel.textColor = [UIColor whiteColor];
            wearLabel.textAlignment = NSTextAlignmentCenter;
            wearLabel.scrollSpeed = 30;
            wearLabel.pauseInterval = 1;
            wearLabel.fadeLength = 12.f;
            wearLabel.scrollDirection = CBAutoScrollDirectionLeft;
            [wearLabel observeApplicationNotifications];
            [_weatherBackView addSubview:wearLabel];
            [wearLabel mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.mas_equalTo(@5);
                make.top.mas_equalTo(@160);
                make.size.mas_equalTo(CGSizeMake(_weatherBackView.frame.size.width, 40));
            }];
        });
        [wearLabel scrollLabelIfNeeded];
    } failure:^(NSError *error) {
        
    }];
    NSDictionary *nameDic = @{@"apikey":APIKEY, @"id":@"1", @"name":@"企业要闻"};
    [NetRequest GET:NEWSCLASS parameters:nameDic success:^(id responseObject) {
        _infoArray = [responseObject[@"yi18"]mutableCopy];
        [_tableView reloadData];
    } failure:^(NSError *error) {
        
    }];
    
}

- (void)startTimer
{
    _time = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(changeDate) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop]addTimer:_time forMode:NSRunLoopCommonModes];
    [[NSRunLoop currentRunLoop]run];
}

- (void)changeDate
{
    //获取系统时间
    if (!_date) {
        _date = [[NSDateFormatter alloc]init];
        
    }
    [_date setDateFormat:@"HH:mm"];
    if (!_dateLabel) {
        //创建时间Label
        _dateLabel = [CustomLabel labelWithFrame:CGRectMake(0, 0, 0, 0) Text:[_date stringFromDate:[NSDate date]] FontSize:40 TextAlignment:NSTextAlignmentLeft TextColor:[UIColor whiteColor] BackGroundColor:[UIColor clearColor] CornerRadius:0 BorderWidth:0 BorderColor:nil];
        [_showView addSubview:_dateLabel];
        [_dateLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(@50);
            make.top.mas_equalTo(@120);
            make.size.mas_equalTo(CGSizeMake(100, 40));
        }];
    }
    _dateLabel.text = [_date stringFromDate:[NSDate date]];
}

@end
